import 'package:flutter/material.dart';
import 'package:flutter_bilibili/core/viewmodel/live_room_view_model.dart';
import 'package:flutter_bilibili/ui/shared/image_assets.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_swiper_null_safety_flutter3/flutter_swiper_null_safety_flutter3.dart';
import 'package:provider/provider.dart';

import '../../../core/model/live_room_model.dart';
import '../../../core/model/live_rooms_model.dart';
import '../../shared/app_theme.dart';
import '../../shared/platform_judge.dart';
import 'live_room_item.dart';

class HYLiveRecommendScreen extends StatefulWidget {
  const HYLiveRecommendScreen({Key? key}) : super(key: key);

  @override
  State<HYLiveRecommendScreen> createState() => _HYLiveRecommendScreenState();
}

class _HYLiveRecommendScreenState extends State<HYLiveRecommendScreen>
    with AutomaticKeepAliveClientMixin {
  late ScrollController _customRecommendScrollController;
  late ScrollController _easyRefreshScrollController;
  late SwiperController _swiperController;
  final List<Widget> _liveRecommendWidgets = [];

  @override
  void initState() {
    _swiperController = SwiperController();
    _customRecommendScrollController = ScrollController();
    _easyRefreshScrollController = ScrollController();
    super.initState();
  }

  @override
  void dispose() {
    _swiperController.dispose();
    _customRecommendScrollController.dispose();
    _easyRefreshScrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Consumer<HYLiveRoomViewModel>(
      builder: (ctx, liveRoomsVM, child) {
        if (liveRoomsVM.recommendLiveRooms.isEmpty) {
          return Container(
            margin: EdgeInsets.only(top: 30.h),
            alignment: Alignment.topCenter,
            width: 1.sw,
            child: const RefreshProgressIndicator(
              value: null,
              color: HYAppTheme.norMainThemeColors,
            ),
          );
        }

        ///前三条数据为轮播图的数据，后面是一行两个的直播间
        return buildLiveRoomList(liveRoomsVM.recommendLiveRooms);
      },
    );
  }

  ///轮播图
  Widget buildLiveSwiperCarousel(List<RecommendRoomList> data) {
    return ClipRRect(
      borderRadius: BorderRadius.circular(4.r),
      child: Container(
        margin: const EdgeInsets.only(bottom: 8).r,
        height: 240.h, //这里的轮播图组件必须包裹在有高度的控件或者设置比例
        child: Swiper(
          controller: _swiperController,
          scale: PlatformJudge.platformJudgeIsPhone() ? 1 : .7,
          viewportFraction: PlatformJudge.platformJudgeIsPhone() ? 1 : .7,
          itemBuilder: (ctx, index) {
            return FadeInImage(
              fit: BoxFit.fill,
              placeholderFit: BoxFit.fill,
              placeholder: AssetImage(ImageAssets.icUpperVideoDefaultPNG),
              image: NetworkImage(
                data[index].cover,
              ),
            );
          },
          itemCount: data.length,
          // indicatorLayout: PageIndicatorLayout.SCALE,
          autoplayDelay: 3000,
          pagination: SwiperPagination(
            alignment: Alignment.bottomRight,
            margin:
                const EdgeInsets.only(left: 0, right: 8, bottom: 8, top: 0).r,
          ),
          fade: 1.0,
          autoplay: true,
          scrollDirection: Axis.horizontal,
        ),
      ),
    );
  }

  ///所有直播
  Widget buildLiveRoomList(List<RecommendRoomList> data) {
    ///动态添加，当窗口变动时，一行里面的子项会调整个数
    if (_liveRecommendWidgets.isEmpty) {
      _liveRecommendWidgets.add(buildLiveRecommend(data));
    }
    return EasyRefresh(
      scrollController: _easyRefreshScrollController,
      child: Column(
        children: _liveRecommendWidgets,
      ),
    );
  }

  Widget buildLiveRecommend(List<RecommendRoomList> data) {
    return CustomScrollView(
      primary: false,
      controller: _customRecommendScrollController,
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      slivers: [
        ///轮播图
        SliverPadding(
          padding: const EdgeInsets.only(top: 8, left: 8, right: 8).r,
          sliver: SliverList(
            delegate: SliverChildBuilderDelegate(
              (ctx, index) {
                ///一个长度的轮播图
                return buildLiveSwiperCarousel(data.sublist(0, 3));
              },
              childCount: 1,
            ),
          ),
        ),

        ///card界面
        SliverPadding(
          padding: const EdgeInsets.symmetric(horizontal: 8).r,
          sliver: SliverGrid(
            delegate: SliverChildBuilderDelegate(
              (ctx, index) {
                RecommendRoomList tempData = data[index];
                return HYLiveRoomItem(
                  LiveRoomModel(
                    areaV2Name: tempData.areaV2Name,
                    cover: tempData.cover,
                    roomid: tempData.roomid,
                    face: tempData.face,
                    watchedShowTextLarge: tempData.watchedShow.textLarge,
                    title: tempData.title,
                    uName: tempData.uname,
                    upId: tempData.upId,
                  ),
                );
              },
              childCount: data.length,
            ),
            gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
              mainAxisExtent: 205.h,
              maxCrossAxisExtent:
                  PlatformJudge.platformJudgeIsPhone() ? 180.w : 100.w,
            ),
          ),
        )
      ],
    );
  }

  @override
  bool get wantKeepAlive => true;
}
